<template>
  <div class="image-upload">
    <el-upload
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :limit="limit"
      :on-preview="preview"
      :class="{ disabled:fileShow}"
      :on-remove="handleRemove"
      :http-request="handleUpload"
      :on-change="handleChange"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条组件 -->
    <el-dialog width="600px" top="8vh" title="图片预览" :visible.sync="showDialog">
      <img width="100%" :src="imgUrl" alt="">
    </el-dialog>
  </div>

</template>

<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
const cos = new COS({
  SecretId: 'AKIDsYy70cJn1ye4D5gz3qMbZGgphJeiW6SZ', // 身份识别ID
  SecretKey: 'tYy95nGUTDj14sTmoZ4IEtHODl22lDOL' // 身份秘钥
})
export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: '',
      percent: 0
    }
  },
  computed: {
    fileShow() {
      return this.fileList.length >= this.limit
    },
    isAllUploadSuccess() {
      // every 必须每个fileList中的项，status属性都要是success才返回true
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    // 预览部分
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    // 处理删除图片
    handleRemove(file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    // 上传
    handleUpload(params) {
      if (params.file) {
        const uid = params.file.uid
        const fileObj = this.fileList.find(item => item.uid === uid)
        fileObj.status = 'uploading'
        cos.putObject({
          Bucket: 'shouxi-1257985108', /* 必须 */
          Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
          Key: parseInt(Math.random() * 999999) + params.file.name, /* 必须 */
          StorageClass: 'STANDARD',
          Body: params.file,
          onProgress: (progressData) => {
            fileObj.percentage = parseInt(progressData.percent * 100)
          }
        }, function(err, data) {
          if (err) return console.log(err)
          fileObj.url = 'https://' + data.Location

          setTimeout(() => {
            fileObj.status = 'success'
          }, 1000)
        })
        // console.log(err || data)
      }
      console.log(params.file)
    },
    // 处理删除增加文件
    handleChange(file, fileList) {
      this.fileList = [...fileList]
    },
    // 上传前文件校验
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }

      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none
    }
  }
}
</style>
